package cn.jinjimi.app.store.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.app.store.entity.ArticleEntity;

import java.util.List;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;

/**
 * Created by Jinsen on 16/2/19.
 */
public class ArticleDao extends AbstractDao<ArticleEntity, String> {

    private static final String TAG = ArticleDao.class.getSimpleName();

    public final static String TABLENAME = "article";

    public static class Properties {
        public static final Property Id = new Property(0, String.class, "id", true, "_id");
        public static final Property Title = new Property(1, String.class, "title", false, "TITLE");
        public static final Property BaseUrl = new Property(2, String.class, "baseUrl", false, "BASE_URL");
        public static final Property Author = new Property(3, String.class, "Author", false, "AUTHOR");
        public static final Property AuthorId = new Property(4, String.class, "AuthorId", false, "AUTHOR_ID");
        public static final Property Readum = new Property(5, Integer.class, "Readum", false, "READUM");
        public static final Property ReadStatus = new Property(6, Integer.class, "ReadStatus", false, "READ_STATUS");

        public Properties() {
        }
    }


    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        if (db == null) return;
        String constraint = ifNotExists ? "IF NOT EXISTS " : "";
        db.execSQL("CREATE TABLE " + constraint + "\'" + TABLENAME + "\' ("
                + "\'" + Properties.Id.columnName + "\' TEXT PRIMARY KEY ,"
                + "\'" + Properties.Title.columnName + "\' TEXT,"
                + "\'" + Properties.BaseUrl.columnName + "\' TEXT,"
                + "\'" + Properties.Author.columnName + "\' TEXT,"
                + "\'" + Properties.AuthorId.columnName + "\' INTEGER,"
                + "\'" + Properties.Readum.columnName + "\' INTEGER,"
                + "\'" + Properties.ReadStatus.columnName + "\' INTEGER);");
    }

    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        if (db == null) return;
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\'" + TABLENAME + "\'";
        db.execSQL(sql);
    }

    public ArticleDao(DaoConfig config) {
        super(config);
    }

    public ArticleDao(DaoConfig config, AbstractDaoSession daoSession) {
        super(config, daoSession);
    }

    @Override
    protected ArticleEntity readEntity(Cursor cursor, int offset) {
        ArticleEntity articleEntity = new ArticleEntity();
        articleEntity.setId(cursor.getString(offset + 0));
        articleEntity.setTitle(cursor.getString(offset + 1));
        articleEntity.setBaseUrl(cursor.getString(offset + 2));
        articleEntity.setAuthor(cursor.getString(offset + 3));
        articleEntity.setAuthorId(cursor.getInt(offset + 4));
        articleEntity.setReadum(cursor.getInt(offset + 5));
        articleEntity.setReadStatus(cursor.getInt(offset + 6));
        return articleEntity;
    }

    @Override
    protected String readKey(Cursor cursor, int offset) {
        return cursor.getString(offset + 0);
    }

    @Override
    protected void readEntity(Cursor cursor, ArticleEntity entity, int offset) {
        entity.setId(cursor.getString(offset + 0));
        entity.setTitle(cursor.getString(offset + 1));
        entity.setBaseUrl(cursor.getString(offset + 2));
        entity.setAuthor(cursor.getString(offset + 3));
        entity.setAuthorId(cursor.getInt(offset + 4));
        entity.setReadum(cursor.getInt(offset + 5));
        entity.setReadStatus(cursor.getInt(offset + 6));
    }

    @Override
    protected void bindValues(SQLiteStatement stmt, ArticleEntity entity) {
        stmt.clearBindings();

        String id = entity.getId();
        if (id != null) {
            stmt.bindString(1, id);
        }

        String title = entity.getTitle();
        if (title != null) {
            stmt.bindString(2, title);
        }

        String baseUrl = entity.getBaseUrl();
        if (baseUrl != null) {
            stmt.bindString(3, entity.getBaseUrl());
        }

        String author = entity.getAuthor();
        if (author != null) {
            stmt.bindString(4, author);
        }

        int authorId = entity.getAuthord();
        if (authorId > -1) {
            stmt.bindLong(5, Long.valueOf(authorId));
        }

        int readum = entity.getReadum();
        if (readum > -1) {
            stmt.bindLong(6, Long.valueOf(readum));
        }

        int readStatus = entity.getReadtatus();
        if (readStatus > -1) {
            stmt.bindLong(7, Long.valueOf(readStatus));
        }

    }

    @Override
    protected String updateKeyAfterInsert(ArticleEntity entity, long rowId) {
        return entity.getId();
    }

    @Override
    protected String getKey(ArticleEntity entity) {
        return entity.getId();
    }

    @Override
    protected boolean isEntityUpdateable() {
        return true;
    }

    /**
     * 根据ID获取文章数据
     *
     * @param ids
     * @return
     */
    public List<ArticleEntity> findArticleByIdsLocal(List<String> ids) {
        if (ids == null || ids.isEmpty())
            return null;
        LogUtil.d(TAG, "ids size " + ids.size());

        if (db != null) {
            String where = new StringBuilder().append(Properties.Id.columnName)
                    .append(" IN ").append(buildInWhereStr(ids)).toString();

            String sqlStr = "SELECT * FROM " + TABLENAME + " where " + where;
            Cursor cursor = db.rawQuery(sqlStr, null);

            return loadAllAndCloseCursor(cursor);

        }
        return null;
    }


    /**
     * 根据文章ID查看是否已阅读
     *
     * @param ids
     * @return
     */
    public synchronized List<ArticleEntity> findArticleReadedByIdsLocal(List<String> ids) {

        if (ids == null || ids.isEmpty())
            return null;

        LogUtil.d(TAG, "ids size " + ids.size());

        if (db != null) {
            String where = new StringBuilder().append(Properties.Id.columnName)
                    .append(" IN ").append(buildInWhereStr(ids)).append(" and ").append(Properties.ReadStatus.columnName)
                    .append(" = ?").toString();

            Cursor cursor = db.query(TABLENAME, null, where, new String[]{String.valueOf(ArticleEntity.STATUS_USER_HAS_READED)}, null, null, null);
            return loadAllAndCloseCursor(cursor);

        }
        return null;
    }

    private String buildInWhereStr(List<String> ids) {
        if (ids != null && ids.size() > 0) {
            StringBuffer sb = new StringBuffer("(");
            int index = 0;
            for (String str : ids) {
                sb.append("\'");
                sb.append(str);
                sb.append("\'");
                if (index < ids.size() - 1) {
                    index++;
                    sb.append(",");
                }
            }
            sb.append(")");

            return sb.toString();
        }
        return "";
    }

}
